﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace Lilium.Web.Mvc
{
	public sealed class ModelErrors: IModelErrors
	{
		public ModelErrors()
		{
			m_Errors = new Dictionary<string, string>();
		}

		public ModelErrors(ModelErrors errors)
		{
			if (errors == null) throw new ArgumentNullException("errors");

			m_Errors = new Dictionary<string, string>(errors.m_Errors);
		}

		#region IModelErrors Members

		public void CopyToModelState(ModelStateDictionary modelStateDictionary)
		{
			if (modelStateDictionary == null) throw new ArgumentNullException("modelStateDictionary");

			foreach (var pair in Errors)
				modelStateDictionary.AddModelError(pair.Key, pair.Value);
		}

		public string GetCombinedMessage()
		{
			if (HasErrors)
			{
				var builder = new StringBuilder();
				foreach (var pair in Errors)
					builder.Append(pair.Value);
				return builder.ToString();
			}
			else return string.Empty;
		}

		public void AddModelError(string key, string value)
		{
			Errors[key] = value;
			OnAddError(EventArgs.Empty);
		}

		#region public bool HasErrors

		public bool HasErrors
		{
			get
			{
				return Errors.Count > 0;
			}
		}

		#endregion

		#endregion
		
		#region public event EventHandler<EventArgs> AddError

		public event EventHandler<EventArgs> AddError;

		private void OnAddError(EventArgs args)
		{
			var handler = AddError;
			if (handler != null)
				handler(this, args);
		}

		#endregion
		
		#region private Dictionary<string, string> Errors

		private readonly Dictionary<string, string> m_Errors;

		private Dictionary<string, string> Errors
		{
			get
			{
				return m_Errors;
			}
		}

		#endregion
	}
}
